package com.neusmart.common.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;

import java.lang.ref.WeakReference;

/**
 * Vertical Image Span
 * <p/>
 * roy
 */
public class VerticalImageSpan extends ImageSpan {

    private WeakReference<Drawable> mDrawableRef;
    private double ratio;

    public VerticalImageSpan(Context context, int resourceId, int verticalAlignment) {
        super(context, resourceId, verticalAlignment);
    }

    public VerticalImageSpan(Context context, int resourceId) {
        super(context, resourceId, DynamicDrawableSpan.ALIGN_BASELINE);
    }

    public VerticalImageSpan(Drawable d) {
        super(d);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        Drawable d = getCachedDrawable(paint);
        Rect rect = d.getBounds();
        if (fm != null) {
            Paint.FontMetricsInt fontMetrics = new Paint.FontMetricsInt();
            paint.getFontMetricsInt(fontMetrics);

            fm.ascent = fontMetrics.ascent;
            fm.descent = fontMetrics.descent;

            fm.top = fontMetrics.top;
            fm.bottom = fontMetrics.bottom;
        }
        return rect.right;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        Drawable d = getCachedDrawable(paint);
        canvas.save();
        int transY;
        Paint.FontMetricsInt fontMetrics = new Paint.FontMetricsInt();
        paint.getFontMetricsInt(fontMetrics);
        transY = y + fontMetrics.ascent;
        canvas.translate(x, transY);
        d.draw(canvas);
        canvas.restore();
    }

    private Drawable getCachedDrawable(Paint paint) {
        WeakReference<Drawable> wr = mDrawableRef;
        Drawable d = null;
        if (wr != null)
            d = wr.get();
        if (d == null) {
            d = getDrawable();
            d.setBounds(new Rect(0, 0, (int) (paint.getFontMetricsInt(null) * ratio), paint.getFontMetricsInt(null)));
            mDrawableRef = new WeakReference<>(d);
        }
        return d;
    }

    public void setRatio(double ratio) {
        this.ratio = ratio;
    }

}
